<?php
/**格式化输出数组
 * @param $array
 */
function dump($array){
    echo '<pre>';
    print_r($array);
    echo '</pre>';
}

/**json格式化
 * @param $data
 * @param string $action
 * @return array|mixed
 */
 
/*过滤html标签*/
function cleanhtml($str,$tags='<img><a><table><tr><td>'){//过滤时默认保留html中的<a><img>标签
	$search = array(
					'@<script[^>]*?>.*?</script>@si',  // Strip out javascript
/*                      '@<[\/\!]*?[^<>]*?>@si',            // Strip out HTML tags*/
					'@<style[^>]*?>.*?</style>@siU',    // Strip style tags properly 
					'@<![\s\S]*?--[ \t\n\r]*>@'         // Strip multi-line comments including CDATA 
	); 
	$str = preg_replace($search, '', $str);
	$str = strip_tags($str,$tags);
	return $str;
}
 
function json_data($data, $action='encode'){
    if($action=='encode'){
        if(!function_exists('unidecode')){
            function unidecode($match){
                return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');
            }
        }
        return preg_replace_callback('/\\\\u([0-9a-f]{4})/i', 'unidecode', json_encode($data));
    } else {
        return (array)json_decode($data, true);
    }
}

function password($password) { //密码加密
    $password = md5($password);
    $password = substr($password, 0, 5) . substr($password, 10, 20) . substr($password, -5) . 'www.ly200.com';
    return md5($password . $password);
}

/**输出json
 * @param string $msg
 * @param int $ret
 */
function e_json($msg='', $ret=0){
    is_bool($ret) && $ret=$ret?1:0;
    exit(json_data(array(
            'msg'	=>	$msg,
            'ret'	=>	$ret
        )
    ));
}

/**获取绝对路径
 * @return mixed
 */
function root_path(){
    $RealPath = realpath( './' );
    $SelfPath = $_SERVER['PHP_SELF'];
    $SelfPath = substr( $SelfPath, 0, strrpos( $SelfPath, '/' ) );
    return str_replace( '\\' ,'/' , substr( $RealPath, 0, strlen( $RealPath ) - strlen( $SelfPath ) ) );
}

/**设置表头
 * @return string
 */
function set_base($dir=''){
    $link = base_url('/application/').'/views/'.THEME_PATH.'/';
    if($dir){
        $link = $link.$dir.'/';
    }
    return "<base href='".$link."' />\n";
}

/**分页函数
 * @param $page
 * @param $total_pages
 * @param $query_string
 * @param $row_count
 * @param string $pre_page
 * @param string $next_page
 * @param int $base_page
 * @return string
 */
function turn_page($page, $total_pages, $query_string, $row_count, $pre_page='<<', $next_page='>>', $base_page=3,$css){	//翻页
	if(!$row_count){return '';}
	$i_start=$page-$base_page>0?$page-$base_page:1;
	$i_end=$page+$base_page>=$total_pages?$total_pages:$page+$base_page;
	($total_pages-$page)<$base_page && $i_start=$i_start-($base_page-($total_pages-$page));
	$page<=$base_page && $i_end=$i_end+($base_page-$page+1);
	$i_start<1 && $i_start=1;
	$i_end>=$total_pages && $i_end=$total_pages;
	$turn_page_str='';
	$pre=$page-1>0?$page-1:1;
	$turn_page_str.= '<ul class="pagination" '.$css.'>';
	//$turn_page_str.=	'<li><a href="'.$query_string.$i_start.'">First</a></li>';
	$turn_page_str.=	'<li><a href="'.$query_string.$pre.$html_ext.'" class="page_button">'.$pre_page.'</a></li>';	
	for($i=$i_start; $i<=$i_end; $i++){
		$turn_page_str.=$page!=$i?"<li><a href='{$query_string}{$i}{$html_ext}'>$i</a></li>":"<li class='active'><a href='javascript:void(0)'>$i</a></li>";
	}
	//$i_end<$total_pages && $turn_page_str.="<li>...<a href='{$query_string}{$total_pages}{$html_ext}'>$total_pages</a></li>";
    $i_end<$total_pages && $turn_page_str.="<li><a href='{$query_string}{$total_pages}{$html_ext}'>...</a></li>";
	$next=$page+1>$total_pages?$total_pages:$page+1;
	$page>=$total_pages && $page--;
	$turn_page_str.="<li><a href='$query_string$next$html_ext'>$next_page</a></li>";
	//$turn_page_str.='<li><a href="'.$query_string.$i_end.'">Last</a></li>';
	$turn_page_str.='</ul>';
	return $turn_page_str;
}
/**
返回类型：string
$un array
*/
function query_string($un=''){	//组织url参数
	!is_array($un) && $un=array($un);
	if($_SERVER['QUERY_STRING']){
		$q=@explode('&', $_SERVER['QUERY_STRING']);
		$v='';
		for($i=0; $i<count($q); $i++){
			$t=@explode('=', $q[$i]);
			if(in_array($t[0], $un)){
				continue;
			}
			$v.=$t[0].'='.urlencode(urldecode($t[1])).'&';
		}
		$v=substr($v, 0, -1);
		$v=='=' && $v='';
		return $v;
	}else{
		return '';
	}
}

function img_width_height($show_img_width, $show_img_height, $picpath, $echo_width_height=1){   //按比例缩小图片
    if(is_file($picpath)){
        $img_info   = getimagesize($picpath);
        $width      = $img_info[0];
        $height     = $img_info[1];

        if($width>$show_img_width){
            $ratio=$width/$show_img_width;
            $width=floor($width/$ratio);
            $height=floor($height/$ratio);
        }
        if($height>$show_img_height){
            $ratio=$height/$show_img_height;
            $width=floor($width/$ratio);
            $height=floor($height/$ratio);
        }
        if($echo_width_height==1){
            return "width='$width' height='$height'";
        }else{
            return array($width, $height);
        }
    }
    return '';
}

function get_data($array,$obj=''){
    $data=array();
    foreach($array as $k=>$v){
        if(strstr($k,'-mod')){
            $filed=str_replace('-mod','',$k);
            $data[$filed]=$v;
        }
    }
    return $data;
}

function get_ext_name($filename=''){   //返回文件后辍名（小写）
    return strtolower(pathinfo($filename, PATHINFO_EXTENSION));
}

/**加载静态文件
 * @return string
 */
function load_static(){
    $static='';
    $args=func_get_args();
    foreach($args as $v){
        if(!$v){continue;}
        if(is_array($v)){
            $attr=$v[1];
            $v=$v[0];
        }
        $ext_name=get_ext_name($v);
        if($ext_name=='css'){
            $static.="<link href='{$v}' rel='stylesheet' type='text/css' $attr />\r\n";
        }elseif($ext_name=='js'){
            $static.="<script type='text/javascript' src='{$c['domain']['static']}{$v}{$refresh}' $attr></script>\r\n";
        }
    }
    return $static;
}

function upload($picpath,$type,$config){
	$root		= $config['root'];
	$path_ary	= explode("/", $picpath);
	$file_name 	= $path_ary[count($path_ary)-1];
	$new_file   = '/static/upload/'.$type.'/'.$file_name;
	rename($root.$picpath, $root.$new_file);
	return $new_file;
}

function resize($file,$config,$thum_size){
	$CI =& get_instance();
    $root = $config['root'];
    $thumb_size_ary = explode(',',$thum_size);
    foreach ($thumb_size_ary as $k1 => $v1){
        $ary = explode('X',$v1);
        $w   = $ary[0];
        $h   = $ary[1];
        $config['image_library']  = 'gd2';
        $config['source_image']   = $root.$file;
        $config['create_thumb']   = TRUE;
        $config['maintain_ratio'] = TRUE;
        $config['thumb_marker']   = '_'.$w.'X'.$h;
        $config['width']          = $w;
        $config['height']         = $h;
        $CI->image_lib->initialize($config);
        $CI->image_lib->resize();
    }
}

/**
 * 批量删除数据表里面的图片(包括缩略图)
 */
function del_img($db_name,$db,$config,$where,$field,$root){
    $item       = $db->get_one($db_name,$where);
    $file       = $item[$field];
    $ary        = explode(',',$config);
    $ext_name   = get_ext_name($file);
    foreach($ary as $k=>$v){
        $ary = explode('X',$v);
        $w   = $ary[0];
        $h   = $ary[1];
        $del_file = str_replace('.'.$ext_name,'_'.$w.'X'.$h.'.'.$ext_name,$file);
        @unlink($root.$del_file);
    }
    @unlink($root.$file);
    $db->update($db_name,$where,array($field=>''));
}

function get_ip(){
    $CI =& get_instance();
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip=$_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }else {
        $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}
function cut_str($str, $lenth, $start=0){	//剪切字符串
    $str=str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&', '"', '<', '>'), $str);
    $len=strlen($str);
    if($len<=$length){
        return str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $str);
    }
    $substr='';
    $n=$m=0;
    for($i=0; $i<$len; $i++){
        $x=substr($str, $i, 1);
        $a=base_convert(ord($x), 10, 2);
        $a=substr('00000000'.$a, -8);
        if($n<$start){
            if(substr($a, 0, 3)==110){
                $i+=1;
            }elseif(substr($a, 0, 4)==1110){
                $i+=2;
            }
            $n++;
        }else{
            if(substr($a, 0, 1)==0){
                $substr.=substr($str, $i, 1);
            }elseif(substr($a, 0, 3)==110){
                $substr.=substr($str, $i, 2);
                $i+=1;
            }elseif(substr($a, 0, 4)==1110){
                $substr.=substr($str, $i, 3);
                $i+=2;
            }else{
                $substr.='';
            }

            if(++$m>=$lenth){
                break;
            }
        }
    }
    return str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $substr);
}
?>